//
//  ViewController.m
//  getPostDemo
//
//  Created by wanglei on 17/2/22.
//  Copyright © 2017年 wanglei. All rights reserved.
//

#import "ViewController.h"

#define BASE_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
//把上面的数字换成两部分 以 ？为分界线
#define URL_POST1 @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
#define URL_POST2 @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"

@interface ViewController ()<NSURLConnectionDataDelegate>
@property(nonatomic,strong)NSMutableArray <NewsModel *>*dataArray;
@property(nonatomic,strong)NSMutableData *tempData;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];


}

#pragma mark ----------------GET同步--------------
-(IBAction)getTong:(UIButton *)sender{
    // 1 创建URL对象
    NSURL *url = [NSURL URLWithString:BASE_URL];
    
    // 2 创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // 2.1 创建请求方式 (默认是get这一步可以不写)
    [request setHTTPMethod:@"get"];
    
    // 3 创建响应对象(有时会出错)
    NSURLResponse *response= nil;
    
    // 4 创建连接对象(同步)
    NSError *error;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
   
    // http://www.jianshu.com/p/bbe7c88d5756
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSNumber *lastUpdateTime = dict[@"lastUpdateTime"];
    NSLog(@"lastUpdateTime = %@",lastUpdateTime);
    NSArray *Array = dict[@"news"];
    self.dataArray = [NewsModel mj_objectArrayWithKeyValuesArray:Array];
    
    for (NewsModel *newsModal in self.dataArray) {
        NSLog(@"newsModal.title = %@",newsModal.title);
    }
}

#pragma mark ---------------POST同步-----------------
- (IBAction)postAction1:(UIButton *)sender {
    NSLog(@"Post同步");
    
    //1 创建URL对象
    NSURL *url =[NSURL URLWithString:URL_POST1];
    
    //2 创建请求对象
    NSMutableURLRequest *resuest =[NSMutableURLRequest requestWithURL:url];
    
    //2.1 创建请求方式
    [resuest setHTTPMethod:@"post"];//get可以省略 但是post必须要写
    
    //3 设置请求参数
    NSData *tempData = [URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
    [resuest setHTTPBody:tempData];//设置请求主体 外界看不见数据
    //4 创建响应对象
    NSURLResponse *response = nil;
    
    //5 创建连接对象
    NSError *error;
    NSData *data = [NSURLConnection sendSynchronousRequest:resuest returningResponse:&response error:&error];
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    
    
    NSNumber *lastUpdateTime = dict[@"lastUpdateTime"];
    NSLog(@"lastUpdateTime = %@",lastUpdateTime);
    NSArray *Array = dict[@"news"];
    self.dataArray = [NewsModel mj_objectArrayWithKeyValuesArray:Array];
    
    for (NewsModel *newsModal in self.dataArray) {
        NSLog(@"newsModal.title = %@",newsModal.title);
    }

}





#pragma mark ---------------GET connection异步-----------------
-(IBAction)getYibu:(UIButton *)sender{
    
    NSURL *url = [NSURL URLWithString:BASE_URL];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:10];
    //连接服务器
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
    
}


//NSURLConnectionDataDelegate代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
{
    NSLog(@"didReceiveResponse");
    _tempData = [NSMutableData data];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;{
    NSLog(@"didReceiveData");
      [_tempData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;{
    _dataArray = [NSMutableArray arrayWithCapacity:1];
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_tempData options:NSJSONReadingAllowFragments error:nil];
    
    
    NSNumber *lastUpdateTime = dict[@"lastUpdateTime"];
    NSLog(@"lastUpdateTime = %@",lastUpdateTime);
    NSArray *Array = dict[@"news"];
    self.dataArray = [NewsModel mj_objectArrayWithKeyValuesArray:Array];
    
    for (NewsModel *newsModal in self.dataArray) {
        NSLog(@"newsModal.title = %@",newsModal.title);
    }
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"%@",error);
}




#pragma mark --------------GET Session异步请求-----------------

- (IBAction)getSession:(UIButton *)sender {
    NSURL *url =[NSURL URLWithString:BASE_URL];
    
    //创建session对象
    NSURLSession *session =[NSURLSession sharedSession];
    __weak typeof(self)temp =self;
    //创建task（该方法内部默认使用get）直接进行传递url即可
    NSURLSessionDataTask *dataTask =[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        temp.dataArray = [NSMutableArray arrayWithCapacity:1];
        //数据操作
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        NSNumber *lastUpdateTime = dict[@"lastUpdateTime"];
        NSLog(@"lastUpdateTime = %@",lastUpdateTime);
        NSArray *Array = dict[@"news"];
        self.dataArray = [NewsModel mj_objectArrayWithKeyValuesArray:Array];
        
        for (NewsModel *newsModal in self.dataArray) {
            NSLog(@"newsModal.title = %@",newsModal.title);
        }
        
        NSLog(@"idStr = %@",self.dataArray[1].type);
        
    }];
    
    //数据操作
    [dataTask resume];
    // 注意数据操作之后无法获得数据
    for (NewsModel *newsModal in self.dataArray) {
        NSLog(@"newsModal.title = %@",newsModal.title);
    }
    
}

#pragma mark -------POST Session异步请求---------

- (IBAction)postSession:(UIButton *)sender {
    //创建URL对象
    NSURL *url =[NSURL URLWithString:URL_POST1];
    //创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"post"];
    NSData *tempdata = [URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:tempdata];
    // 3 建立会话 session支持三种类型的任务
    
    //    NSURLSessionDataTask  //加载数据
    //    NSURLSessionDownloadTask  //下载
    //    NSURLSessionUploadTask   //上传
    NSURLSession *session =[NSURLSession sharedSession];
    //    NSLog(@"%d",[[NSThread currentThread] isMainThread]);
    
    __weak typeof(self)weakSelf = self;
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //解析
        _dataArray = [NSMutableArray arrayWithCapacity:1];
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        
        NSNumber *lastUpdateTime = dict[@"lastUpdateTime"];
        NSLog(@"lastUpdateTime = %@",lastUpdateTime);
        NSArray *Array = dict[@"news"];
        self.dataArray = [NewsModel mj_objectArrayWithKeyValuesArray:Array];
        
        for (NewsModel *newsModal in weakSelf.dataArray) {
            NSLog(@"newsModal.title = %@",newsModal.title);
        }
        
        NSLog(@"当前的线程为%@",[NSThread currentThread]);
        //回到主线程 刷新数据 要是刷新就在这里面
        dispatch_async(dispatch_get_main_queue(), ^{
            
            for (NewsModel *model in weakSelf.dataArray) {
                NSLog(@"summary = %@",model.summary);
            }
            
        });
    }];
    //启动任务
    [dataTask resume];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
